package com.sx.pipeline.ui.wallet.recharge

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.sx.mvvmlibs.base.EasyAdapter
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.view.SpaceItemDecoration
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.RechargeAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActRechargeBinding
import com.sx.pipeline.event.PayResultEvent
import com.sx.pipeline.repos.http.res.RechargeInfoVO
import com.sx.pipeline.wxapi.PayHelper
import com.sx.pipeline.wxapi.WXPayEntryActivity
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 充值
 */
@Route(path = RoutePath.Wallet.RECHARGE)
class RechargeActivity :
    CYDataBindingBaseActivity<ActRechargeBinding, RechargeVM>(R.layout.act_recharge),
    View.OnClickListener {

    private val SDK_PAY_FLAG: Int = 1
    private val SDK_AUTH_FLAG: Int = 2

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        @Suppress("unused")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult: PayResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        PayResultEvent(true, "支付成功", WXPayEntryActivity.targetPage).let {
                            RxBus.getDefault().post(it)
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LogUtils.i("${payResult}")
                        PayResultEvent(false, "支付失败", WXPayEntryActivity.targetPage).let {
                            RxBus.getDefault().post(it)
                        }
                    }
                }

                else -> {}
            }
        }
    }

    private var mAdapter: RechargeAdapter? = null

    private var rechargeId = 0

    var subtie: Disposable? = null

    override fun initData() {
        registerRxbus()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        mViewModel.getRechargeList()
    }


    private fun initRv(categoryChild: List<RechargeInfoVO>) {
        mAdapter = RechargeAdapter(this, categoryChild)
        mBinding.recyclerView.layoutManager =
            StaggeredGridLayoutManager(3, GridLayoutManager.VERTICAL)
        mBinding.recyclerView.addItemDecoration(
            SpaceItemDecoration(10)
        )
        mBinding.recyclerView.setAdapter(mAdapter)
        mAdapter?.setSelectMode(EasyAdapter.SelectMode.SINGLE_SELECT)
        mAdapter?.setOnItemClickListener {

        }
        mAdapter?.setSelected(0)
        //监听多选
        mAdapter?.setOnItemSingleSelectListener { itemPosition, isSelected ->
            mBinding.tvMoney.text =
                mViewModel.rechargeListEvent.value?.get(itemPosition)?.rechargeMoney
            rechargeId = mViewModel.rechargeListEvent.value?.get(itemPosition)?.id!!
        }

    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.rechargeListEvent) {
            it?.let { it1 -> initRv(it1) }
            if (it?.size != 0) {
                mBinding.tvMoney.text = it!![0].rechargeMoney
                rechargeId = it!![0].id
            }
        }

        //微信充值
        observe(mViewModel.rechargeDataEvent) {
            PayHelper.getInstance().WexPay(this, it)
        }

        //支付宝充值
        observe(mViewModel.rechargeAliPayDataEvent) {
            ThreadUtils.executeByIo(object : ThreadUtils.SimpleTask<Map<String, String>>() {
                override fun doInBackground(): Map<String, String> {
                    val alipay: PayTask = PayTask(this@RechargeActivity)
                    val result: Map<String, String> = alipay.payV2(it, true)
                    return result
                }

                override fun onSuccess(result: Map<String, String>?) {
                    ThreadUtils.getMainHandler().post {
                        val msg = Message()
                        msg.what = SDK_PAY_FLAG
                        msg.obj = result
                        mHandler.sendMessage(msg)
                    }
                }
            })
        }
    }


    @SuppressLint("CheckResult")
    private fun registerRxbus() {
        //下拉刷新
        val payResultEvent = PayResultEvent::class.java
        subtie = RxBus.getDefault().toObservableSticky(payResultEvent)
            .subscribeOn(Schedulers.io())
            .subscribe {
                val bundle = Bundle()
                bundle.putSerializable(IntentKey.DATA, it)
                ARouter.getInstance().build(RoutePath.Wallet.RECHARGE_RESULT)
                    .with(bundle).navigation()
            }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //立即支付
            R.id.tv_pay -> {
                if (mBinding.rbWx.isChecked) {
                    mViewModel.sumitWxRecharge(rechargeId)
                } else {
                    mViewModel.sumitAliPayRecharge(rechargeId)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (subtie != null) {
            if (!subtie!!.isDisposed()) {
                subtie!!.dispose();
            }
        }
    }

}